import axios from 'axios'
import Vue from 'vue'


const root = process.env.VUE_APP_BASE_API
axios.defaults.baseURL = root

// 全局定义错误处理
axios.interceptors.response.use((res) => {
  return res
}, (err) => {
  Vue.prototype.$message({
    type: 'error',
    message: err
  })
  return console.log(err)
})

// 拦截请求验证token
axios.interceptors.request.use((config) => {
  // Do something before request is sent
  config.headers.Authorization = 'Bearer ' + localStorage.token

  return config
}, function (error) {
  Vue.prototype.$message({
    type: 'error',
    message: error
  })
  return console.log(error)
})



// http
export default function (url, data = {}, method = 'get') {
  if (method === 'get' || method === 'GET') {
    let arr = Object.keys(data)
    let strLast = ''
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      strLast = strLast + item + '=' + data[item] + '&'
    }
    if (strLast) {
      strLast = '?' + strLast.substring(0, strLast.length - 1)
    }
    url = url + strLast
    return axios.get(url)
  } else {
    return axios.post(url, data)
  }
}
